2.6 代码结构调整(临时方案)
当URL很多的时候,会出现代码太长,不好管理,所以可以再在包里面再建一个py文件。 然后将部份代码移入到新建的py文件。然后可以分类注释管理
1、新建文件迁移代码
from django.conf import settings
from django.shortcuts import HttpResponse,redirect
import os.path
#视图函数,必需有一个参数
def hello(request):
filepath=os.path.join(settings.BASE_DIR, "shn" , "hello_world.html" )
with open (filepath, "r" ) as f:
content=f.read()
return HttpResponse(content,content_type= "text/html" ,status=200)
def year_archive(requeet,year): # 传入动态URL(yaer)
return HttpResponse("这是导入re_path的年份")
def month_archive(requeet,month,year): # 传入动态URL(yaer,month)
return HttpResponse("这上导入re_path的年月")
2、在URL文件写入连接语句
from .views import * #将views导入
from django.urls import path,re_path #需要导入re_path库
from django.contrib import admin
from .views import * #将views导入
urlpatterns = [
path( 'admin/' , admin.site.urls),
path( 'hello' , hello), # re_path(r"^ariticles/([0-9]{4})$", year_archive) , #无名分组
re_path(r "^ariticles/(?P <year >[0-9]{4})/(?P <month >[0-9]{2})$" , month_archive), # 有名分组,P必须是大写的,不然会报错
]